package org.tinyweb.render;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TextRender extends Render {
    private static final Logger LOGGER = LoggerFactory.getLogger(TextRender.class);
    private static final String DEFAULT_CONTENT_TYPE = "text/plain;charset=" + getEncoding();
    private String contentType;
    private String text;
    
    public TextRender(String text){
        this.text = text;
    }
    
    public TextRender(String text,String contentType){
        this.text = text;
        this.contentType = contentType;
    }
    
    @Override
    public void render() {
        PrintWriter writer = null;
        try {
            response.setHeader("Pragma", "no-cache");   // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            
            if (contentType == null) {
                response.setContentType(DEFAULT_CONTENT_TYPE);
            } else {
                response.setContentType(contentType);
                response.setCharacterEncoding(getEncoding());
            }
            
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (writer != null){
                writer.close();
            }
        } 
    }
    
}
